/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "dma2d.h"
#include "i2c.h"
#include "rtc.h"
#include "spi.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
// #include "ILI9341_GFX.h"
// #include "ILI9341_STM32_Driver.h"

// #include "5x5_font.h"

#include "stdio.h"
#include "mcu_temper.h"
#include "bsp_aht20.h"
#include "user_printf.h"
#include "rtc_time.h"
#include "ui.h"
#include "ugui.h"




/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */


// 定义一个结构体，用于存储温度，湿度和芯片温度
    struct Temperature_Humidity_Mcu {
        float Temperature;
        float Humidity;
        float Mcu_temperature;
    };
// 定义一个结构体变量，用于存储温度，湿度和芯片温度
    struct Temperature_Humidity_Mcu temperature_humidity_mcu;



char Temp_Buffer[20];
char Humi_Buffer[20];
char Mcu_Buffer[20];
char timeBuffer[21]; // 分配足够的空间以包含字符串和终止符'\0'


/* GUI structure */
UG_GUI gui;

/* Window 1 */
UG_WINDOW window_1;
UG_OBJECT obj_buff_wnd_1[10];
UG_BUTTON button1_1;
UG_BUTTON button1_2;
UG_BUTTON button1_3;
UG_TEXTBOX textbox_1;


/*
实现窗口内控件的回调点击处理函数
*/
void window_1_callback (UG_MESSAGE* msg)
{
    if (msg->type == MSG_TYPE_OBJECT)
    {
        if (msg->id == OBJ_TYPE_BUTTON)
        {
            switch (msg->sub_id)
            {
                case BTN_ID_0 :
                {
                    UG_ButtonSetBackColor(&window_1, BTN_ID_1, RED);
                    break;
                }
                case BTN_ID_1 :
                {
                    // 如果这里不需要执行任何操作，请保留此注释作为说明
                    // 否则，请添加具体的操作代码
                    break;
                }

                case BTN_ID_2 :
                {
                    // 如果这里不需要执行任何操作，请保留此注释作为说明
                    // 否则，请添加具体的操作代码
                    break;
                }

                default:
                {
                    // 处理其他未知的按钮ID
                    // 可以记录日志或者执行默认操作
                    // 例如: printf("Unknown button ID: %d\n", msg->sub_id);
                    break;
                }
            }
        }
        else
        {
            // 处理其他类型的对象消息
            // 例如: printf("Unsupported object type: %d\n", msg->id);
        }
    }
    else
    {
        // 处理其他类型的消息
        // 例如: printf("Unsupported message type: %d\n", msg->type);
    }
}













/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MPU_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MPU Configuration--------------------------------------------------------*/
  MPU_Config();

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SPI1_Init();
  MX_UART5_Init();
  MX_I2C2_Init();
  MX_ADC3_Init();
  MX_RTC_Init();
  MX_DMA2D_Init();
  /* USER CODE BEGIN 2 */
  //ui_init();
	ILI9341_Init();
	AHT20_Init();

	HAL_Delay(900);




/* UGUI初始化 */
  UG_Init(&gui,(void (*)(UG_S16, UG_S16, UG_COLOR))_HW_DrawPoint,320,240);    

  UG_DriverRegister(DRIVER_DRAW_LINE,(void *)_HW_DrawLine);   // 注册画直线的函数
  UG_DriverRegister(DRIVER_FILL_FRAME,(void *)_HW_FillRrame); // 注册填充矩形的函数

  UG_DriverEnable(DRIVER_DRAW_LINE);                          // 启用画直线的函数
  UG_DriverEnable(DRIVER_FILL_FRAME);                         // 启用填充矩形的函数


// UG_WindowCreate(&window_1,obj_buff_wnd_1,10,window_1_callback); // 创建一个窗口

// UG_WindowSetTitleText(&window_1,"uGUI Demo ");                 // 设置窗口的标题
// UG_WindowSetTitleTextFont(&window_1,&FONT_16X26);              // 设置窗口的标题字体
// UG_WindowSetTitleTextColor(&window_1,C_BLACK);                  // 设置窗口的标题颜色
// UG_WindowSetTitleColor(&window_1,C_LIGHT_YELLOW);               // 设置窗口的标题背景颜色
// UG_WindowSetTitleTextAlignment(&window_1,ALIGN_CENTER);         // 设置窗口的标题对齐方式(居中对齐)

// UG_ButtonCreate(&window_1,&button1_1,BTN_ID_0,10,10,100,60);     // 创建一个按钮
// UG_ButtonCreate(&window_1,&button1_2,BTN_ID_6,10,70,100,130);     // 创建一个按钮
// UG_ButtonCreate(&window_1,&button1_3,BTN_ID_2,10,140,100,190);


// UG_ButtonSetFont(&window_1,BTN_ID_0,&FONT_8X12);             // 设置按钮的字体
// UG_ButtonSetText(&window_1,BTN_ID_0,"ABC");               // 设置按钮的文本
// UG_ButtonSetFont(&window_1,BTN_ID_6,&FONT_8X12);             // 设置按钮的字体
// UG_ButtonSetText(&window_1,BTN_ID_6,"ABC");

// UG_ButtonSetFont(&window_1,BTN_ID_2,&FONT_8X12);
// UG_ButtonSetText(&window_1,BTN_ID_2,"ABC");










// UG_WindowShow(&window_1);                                       // 显示窗口

























  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		  AHT20_ReadData(&temperature_humidity_mcu.Temperature, &temperature_humidity_mcu.Humidity);  // 调用AHT20_ReadData函数来读取温度和湿度
  temperature_humidity_mcu.Mcu_temperature = Read_Internal_Temperature(); // 读取芯片温度

  sprintf(Temp_Buffer, "%0.3f Celsius\n", temperature_humidity_mcu.Temperature);
  sprintf(Humi_Buffer, "%0.3f RH\n",temperature_humidity_mcu.Humidity);
  temperature_humidity_mcu.Mcu_temperature = Read_Internal_Temperature();
sprintf(Mcu_Buffer, "%0.3f Celsius\n", temperature_humidity_mcu.Mcu_temperature);
UG_FontSelect(&FONT_8X12);

//UG_FillScreen(C_BLACK);
// //显示环境温度
UG_PutString(10,10,"Temperature:");
UG_PutString(170,10,Temp_Buffer);
// 显示环境湿度
UG_PutString(10,30,"Humidity:");
UG_PutString(170,30,Humi_Buffer);
// 显示芯片温度
UG_PutString(10,50,"Mcu_temperature:");
UG_PutString(170,50,Mcu_Buffer);



// //显示环境温度
// UG_ConsolePutString("Temperature: \n");
// UG_ConsolePutString(Temp_Buffer);
// //显示环境湿度
// UG_ConsolePutString("Humidity: \n");
// UG_ConsolePutString(Humi_Buffer);
// //显示芯片温度
// UG_ConsolePutString("Mcu_temperature: \n");
// UG_ConsolePutString(Mcu_Buffer);
		
    //UG_Update();
		HAL_Delay(10);
  // AHT20_ReadData(&temperature_humidity_mcu.Temperature, &temperature_humidity_mcu.Humidity);  // 调用AHT20_ReadData函数来读取温度和湿度
  // temperature_humidity_mcu.Mcu_temperature = Read_Internal_Temperature(); // 读取芯片温度
  // ui_draw_page_one(temperature_humidity_mcu.Temperature,temperature_humidity_mcu.Humidity,temperature_humidity_mcu.Mcu_temperature);  // 调用ui_draw_page_one函数来绘制界面
	// HAL_Delay(1500);
// 		    /*
//     显示界面
//     */
// 		ILI9341_Draw_Text("STM32H750VBT6", 36, 10, WHITE, 3, BLACK);  //绘制文本
//     ILI9341_Draw_Horizontal_Line(35,42,240,WHITE);    //绘制水平线

//     ILI9341_Draw_Rectangle(10,56,100,30,WHITE);       //绘制圆角矩形
//     ILI9341_Draw_Rectangle(10,96,100,30,WHITE);       //绘制圆角矩形
//     ILI9341_Draw_Rectangle(10,136,100,30,WHITE);       //绘制圆角矩形

//     ILI9341_Draw_Rectangle(140,56,150,30,CYAN);       //绘制圆角矩形
//     ILI9341_Draw_Rectangle(140,96,150,30,CYAN);       //绘制圆角矩形
//     ILI9341_Draw_Rectangle(140,136,150,30,YELLOW);       //绘制圆角矩形



//     ILI9341_Draw_Vertical_Line(120,50,120,YELLOW);    //绘制垂直线
//     ILI9341_Draw_Text("TEM_MCU:", 12, 62, BLACK, 2, WHITE);  //绘制文本
//     ILI9341_Draw_Text("TEM_AMB:", 12, 102, BLACK, 2, WHITE);  //绘制文本
//     ILI9341_Draw_Text("REL_HUM:", 12, 142, BLACK, 2, WHITE);  //绘制文本


//     AHT20_ReadData(&temperature_humidity_mcu.Temperature, &temperature_humidity_mcu.Humidity);
//     sprintf(Temp_Buffer, "%0.3f", temperature_humidity_mcu.Temperature);
//     sprintf(Humi_Buffer, "%0.3f",temperature_humidity_mcu.Humidity);
//     temperature_humidity_mcu.Mcu_temperature = Read_Internal_Temperature();
//     sprintf(Mcu_Buffer, "%0.3f", temperature_humidity_mcu.Mcu_temperature);
//      ILI9341_Draw_Text(Mcu_Buffer, 160, 62, BLACK, 2, CYAN);  //绘制文本
//     ILI9341_Draw_Text(Temp_Buffer, 160, 102, BLACK, 2, CYAN);  //绘制文本
// 		ILI9341_Draw_Text(Humi_Buffer, 160, 142, BLACK, 2, YELLOW);  //绘制文本
		
// // 调用RTC_Time_Send_ToBuffer函数来填充缓冲区
//     RTC_Time_Send_ToBuffer(timeBuffer, sizeof(timeBuffer));

//  Uart5_printf("%s\r\n", timeBuffer);   // 使用串口打印函数打印时间
// ILI9341_Draw_Text(timeBuffer, 35, 210, WHITE, 2, BLACK);  //绘制文本


		//HAL_Delay(10);


		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  __HAL_RCC_SYSCFG_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Configure LSE Drive Capability
  */
  HAL_PWR_EnableBkUpAccess();
  __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 120;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 5;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

 /* MPU Configuration */

void MPU_Config(void)
{
  MPU_Region_InitTypeDef MPU_InitStruct = {0};

  /* Disables the MPU */
  HAL_MPU_Disable();

  /** Initializes and configures the Region and the memory to be protected
  */
  MPU_InitStruct.Enable = MPU_REGION_ENABLE;
  MPU_InitStruct.Number = MPU_REGION_NUMBER0;
  MPU_InitStruct.BaseAddress = 0x0;
  MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
  MPU_InitStruct.SubRegionDisable = 0x87;
  MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
  MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
  MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
  MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;
  MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
  MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;

  HAL_MPU_ConfigRegion(&MPU_InitStruct);
  /* Enables the MPU */
  HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);

}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
